package kotan.view.table;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;

import kotan.Kotan;

/**
 * 
 * @author shuji.w6e
 * @since 1.0
 */
class EntityTableKeyListener extends KeyAdapter {

    /** logger */
    private static Logger logger = Logger.getLogger(EntityTableKeyListener.class.getName());

    final EntityTableView view;
    final EntityTableControl control;

    /**
     * Constructor.
     * @param view
     */
    EntityTableKeyListener(EntityTableView view) {
        this.view = view;
        this.control = view.control;
    }

    @Override
    public void keyPressed(KeyEvent evt) {
        switch (evt.getKeyCode()) {
        case KeyEvent.VK_F2:
            onF2(evt);
            break;
        case KeyEvent.VK_DELETE:
            onDelete(evt);
            break;
        case KeyEvent.VK_ENTER:
            onEnter(evt);
            break;
        default:
            break;
        }
    }

    protected void onF2(KeyEvent evt) {
        int row = view.table.getSelectedRow();
        int col = view.table.getSelectedColumn();
        if (logger.isLoggable(Level.FINE)) logger.fine("onF2: " + row + "," + col);
        if (view.tableModel.getValueAt(row, col) == null) {
            view.tableModel.setDefaultValueAt(row, col);
        }
        if (view.tableModel.isCellSpecialEditable(row, col)) {
            control.editSpecialColumn(row, col);
        }
    }

    protected void onDelete(KeyEvent evt) {
        int row = view.table.getSelectedRow();
        if (row == -1) return;
        if (view.tableModel.isCreateRow(row)) return;
        int col = view.table.convertColumnIndexToModel(view.table.getSelectedColumn());
        if (logger.isLoggable(Level.FINE)) logger.fine("onDelete");
        if (view.tableModel.isKey(col)) {
            Kotan.get().getDatastore().delete(view.tableModel.getKey(row));
        } else {
            control.setNullAt(row, col);
        }
    }

    protected void onEnter(KeyEvent evt) {
        int row = view.table.getSelectedRow();
        int col = view.table.convertColumnIndexToModel(view.table.getSelectedColumn());
        if (row != view.tableModel.getRowCount() - 1 || col != 0) return;
        evt.consume();
        control.createNewEntity();
    }

}
